class Solution {
    static class TreeNode{
        public char val;
        public TreeNode left;
        public TreeNode right;
        public TreeNode(char val){
            this.val = val;
        }
    }
    int getHeight(TreeNode root){
        if (root == null) return 0;
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        return (leftHeight > rightHeight ? leftHeight+1 : rightHeight+1);
    }
    //判断一棵树是不是平衡二叉树
    public boolean isBalanced(TreeNode root) {
        if (root == null){
            return true;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);

        return Math.abs(leftHeight - rightHeight) <= 1 && isBalanced(root.left) && isBalanced(root.right);
    }
    //这个是字节考过原题
    public int maxDepth(TreeNode root){
        if (root == null) return 0;
        int leftHeight = maxDepth(root.left);
        int rightHeight = maxDepth(root.right);
        if (leftHeight >= 0 && rightHeight >= 0 && Math.abs(leftHeight - rightHeight )<= 1){
            return Math.max(leftHeight, rightHeight) + 1;
        }else{
            return -1;
        }
    }
    public boolean isBalanced2(TreeNode root){
        if (root == null){
            return true;
        }
        return maxDepth(root) >= 0;
    }
    //对称二叉树
    public boolean isSymmetric(TreeNode root) {
        if (root == null){
            return true;
        }
        return isSymmetricChild(root.left, root.right);
    }
    private boolean isSymmetricChild(TreeNode leftTree, TreeNode rightTree){
        if (leftTree == null && rightTree != null || leftTree != null && rightTree == null){
            return false;
        }
        if (leftTree == null && rightTree == null){
            return true;
        }
        if (leftTree.val != rightTree.val){
            return false;
        }
        return isSymmetricChild(leftTree.left, rightTree.right) && isSymmetricChild(leftTree.right, rightTree.left);
    }
}
